'use client';

import { ApiResponse, LoginRes, MessageData } from '@/types/interface';
import { useEffect, useMemo, useRef } from 'react';
import UploadFile from './UploadFile';
import http from '@/lib/request';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useImmer } from 'use-immer';
import { marked } from 'marked';
import { enableMapSet } from 'immer';
import { setSesstion } from '@/lib/session';
import { getTxtNode } from '@/lib/nodeUtil';
import StepContainer from './stepContainer';
import { selectClear, selecthistoryData, selectList } from '@/store/initSlice';
import { useAppDispatch, useAppSelector } from '@/store/hooks';

// 自定义图标组件
const ArrowUpIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 10l7-7m0 0l7 7m-7-7v18" />
  </svg>
);

const PauseCircleIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
);

const PlayCircleIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
);

enableMapSet();

/**
 * 右侧聊天展示区域组件
 */
const Right = () => {
	const historyData = useAppSelector(selecthistoryData);
	const curList = useAppSelector(selectList);
	const clear = useAppSelector(selectClear);

	// 使用 Immer 管理会话响应数据映射
	const [mapRes, setMap] = useImmer(
		new Map<
			string,
			{
				dirty: boolean;
				data: string[];
				think: string[];
				node: React.ReactNode;
				mode: string;
			}
		>(),
	);

	const container = useRef<HTMLDivElement>(null);

	/**
	 * 自动滚动到底部
	 */
	const scrollLast = () => {
		const node = container.current?.lastElementChild;
		if (node) {
			node.scrollIntoView({ behavior: 'smooth', block: 'end' });
		}
	};

	/**
	 * 处理消息列表更新，生成对应的 React 节点内容
	 */
	const handleAdd = () => {
		setMap((draft) => {
			// 遍历当前消息列表，填充到 map 中
			curList.forEach((item) => {
				const key = item.node;
				const txt = item.text;

				if (!draft.has(key)) {
					draft.set(key, {
						dirty: false,
						data: [],
						think: [],
						node: null,
						mode: item.model,
					});
				}

				const obj = draft.get(key)!;

				if (item.remark === 'reason') {
					obj.think.push(txt as string);
				} else {
					obj.data.push(txt);
				}
				obj.dirty = true;
			});

			// 更新每个节点的渲染内容
			for (const [key, obj] of draft) {
				if (obj.dirty) {
					if (key === 'GenerateDocument') {
						obj.node = getTxtNode(obj.data.join(''), true);
					} else {
						const contentNode = getTxtNode(
							obj.data.reduce((prev, cur) => prev + cur, ''),
						);
						obj.node = (
							<div>
								<div className="text-sm text-gray-500">
									{getTxtNode(obj.think.join(''))}
								</div>
								{contentNode}
							</div>
						);
					}
					obj.dirty = false;
				}
			}
		});
	};

	/**
	 * 构造用于展示的步骤项
	 */
	const listItems = useMemo(() => {
		return Array.from(mapRes.entries()).map(([key, obj]) => ({
			title: `${key} ${obj.mode || ''}`,
			description: obj.node,
		}));
	}, [mapRes]);

	// 监听 curList 更新，触发消息处理
	useEffect(() => {
		handleAdd();
	}, [curList]);

	// 渲染后自动滚动到底部
	useEffect(() => {
		scrollLast();
	}, [mapRes]);
	useEffect(() => {
		clear && setMap(new Map());
	}, [clear]);

	return (
		<div className="flex-1 overflow-auto">
			<div className="content px-4 sm:px-8 md:px-16 lg:px-40 flex-1 w-full">
				<div className="mb-2">
					<StepContainer messages={historyData} />
					<div ref={container} className="space-y-8">
							{listItems.map((item, index) => (
								<div key={index} className="relative">
									{/* 步骤指示器 */}
									<div className="absolute -left-4 top-1.5 w-6 h-6 rounded-full bg-blue-100 border-2 border-blue-500 flex items-center justify-center">
										<span className="text-xs font-semibold text-blue-600">{index + 1}</span>
									</div>
									
									{/* 步骤内容 */}
									<div className="ml-4">
										{/* 步骤标题 */}
										<div className="text-sm font-medium text-gray-800 mb-2">{item.title}</div>
										
										{/* 步骤描述 */}
										<div className="text-gray-600">{item.description}</div>
									</div>
									
									{/* 连接线（最后一个步骤不显示） */}
									{index < listItems.length - 1 && (
										<div className="absolute -left-1.5 top-8 bottom-0 w-0.5 bg-gray-200"></div>
									)}
								</div>
							))}
						</div>
				</div>
			</div>
		</div>
	);
};

export default Right;
